<script setup lang="ts">
import { onMounted, ref } from 'vue';
import { deleteSourceData, getSourceDataPage } from '@/service/api/source-data';
import DetailModal from './modules/detail.vue';

const loading = ref(false);
const tableData = ref<Api.SourceData.SourceData[]>([]);
const modalVisible = ref(false);
const currentRecord = ref<Api.SourceData.SourceData | null>(null);

const columns = [
  { title: 'ID', dataIndex: 'id', key: 'id' },
  { title: '数据源名称', dataIndex: 'name', key: 'name' },
  { title: '数据源类型', dataIndex: 'type', key: 'type' },
  { title: '描述', dataIndex: 'description', key: 'description' },
  { title: '更新时间', dataIndex: 'updateTime', key: 'updateTime' },
  { title: '操作', key: 'action' }
];

/** 获取表格数据 */
async function fetchTableData() {
  loading.value = true;
  try {
    const { data } = await getSourceDataPage({ current: 1, size: 10 });
    if (data) {
      tableData.value = data.records;
    }
  } finally {
    loading.value = false;
  }
}

/** 处理新增 */
function handleAdd() {
  currentRecord.value = null;
  modalVisible.value = true;
}

/**
 * 处理编辑
 *
 * @param record
 */
function handleEdit(record: Api.SourceData.SourceData) {
  currentRecord.value = { ...record };
  modalVisible.value = true;
}

/**
 * 处理删除
 *
 * @param id
 */
async function handleDelete(id: number) {
  await deleteSourceData(id);
  window.$message?.success('删除成功');
  fetchTableData();
}

/** 处理弹窗确认 */
function handleModalOk() {
  modalVisible.value = false;
  fetchTableData();
}

onMounted(() => {
  fetchTableData();
});
</script>

<template>
  <div>
    <a-card title="源数据管理">
      <a-button type="primary" class="mb-4" @click="handleAdd">新建</a-button>
      <a-table :columns="columns" :data-source="tableData" :loading="loading" row-key="id">
        <template #bodyCell="{ column, record }">
          <template v-if="column.key === 'action'">
            <a-button type="link" @click="handleEdit(record as Api.SourceData.SourceData)">编辑</a-button>
            <a-popconfirm title="确定删除吗?" @confirm="handleDelete(record.id)">
              <a-button type="link" danger>删除</a-button>
            </a-popconfirm>
          </template>
        </template>
      </a-table>
    </a-card>
    <DetailModal v-model:visible="modalVisible" :record="currentRecord" @ok="handleModalOk" />
  </div>
</template>
